package com.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.health.constant.MessageConstant;
import com.health.dao.*;
import com.health.entity.PageResult;
import com.health.entity.QueryPageBean;
import com.health.entity.Result;
import com.health.pojo.*;
import com.health.service.OrderSettingService;
import com.health.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Classname OrderSettingServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/3/16 18:13
 * @Author RainGrd
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
@Slf4j
public class OrderSettingServiceImpl implements OrderSettingService {


    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private OrderDao orderDao;


    @Autowired
    private ReportDao reportDao;

    @Autowired
    private UserDao userDao;


    @Autowired
    private MemberDao memberDao;

    @Autowired
    private SetmealDao setmealDao;

    @Override
    public Result saveOrderSetting(OrderSetting orderSetting) {
        try {
            int i = orderSettingDao.insertOrderSetting(orderSetting);
            return i > 0 ? Result.success() : Result.error(MessageConstant.ORDERSETTING_FAIL);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error();
        }

    }

    @Override
    public int saveOrderSettingList(List<OrderSetting> orderSettingList) {
        int result = 0;
        if (orderSettingList == null && orderSettingList.size() <= 0) {
            return result;
        } else {
            for (OrderSetting orderSetting : orderSettingList) {
                log.info("orderSetting:{}", orderSettingDao);
                //检查此数据（日期）是否存在
                long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if (count > 0) {
                    //已经存在，执行更新操作
                    result = orderSettingDao.updateReservationsByOrderDate(orderSetting);
                } else {
                    //不存在，执行添加操作
                    result = orderSettingDao.insertOrderSetting(orderSetting);
                }

            }
        }
        return result;
    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {
       /* String dateBegin = date + "-1";
        String dateEnd = date + "-31";
        Map map = new HashMap<>();
        map.put("dateBegin", dateBegin);
        map.put("dateEnd", dateEnd);
        log.info("map:{}", map);*/
        List<OrderSetting> orderSettings = orderSettingDao.selectOrderSettingByMonth(date);
        List<Map> data = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings) {
            Map<String, Object> orderSettingMap = new HashMap<>();
            orderSettingMap.put("date", orderSetting.getOrderDate().getDate());//获得日期（几号）
            orderSettingMap.put("number", orderSetting.getNumber());//可预约人数
            orderSettingMap.put("reservations", orderSetting.getReservations());//已预约人数
            data.add(orderSettingMap);
        }
        return data;
    }

    @Override
    public Result editOrderSetting(OrderSetting orderSetting) {
        try {
            long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
            log.info("查询出来的count:{}", count);
            int i = 0;
            if (count > 0) {
                //当前日期已经进行了预约设置，需要进行修改操作
                i = orderSettingDao.updateNumberByOrderDate(orderSetting);
            } else {
                //当前日期没有进行预约设置，进行添加操作
                i = orderSettingDao.insertOrderSetting(orderSetting);
            }
            return i > 0 ? Result.success(MessageConstant.ORDERSETTING_SUCCESS) : Result.error(MessageConstant.ORDERSETTING_FAIL);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error();
        }
    }

    @Override
    public Result queryOrderSettings() {
        return Result.success(orderSettingDao.selectOrderSettings());
    }


    @Override
    public PageResult queryOrderListPage(QueryPageBean queryPageBean, User user) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //根据用户Id查询用户对象
        //查询预约列表
        List<OrderList> orders = orderDao.selectOrderByCondition(queryPageBean.getQueryString(), user);
        /*for (Order order : orders) {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(order, orderDto);
            log.info("orderDto:{}", orderDto);
            System.out.println(orderDto);
            //根据会员id查询会员
            orderDto.setMember(memberDao.findById(orderDto.getMemberId()));
            //根据套餐Id查询套餐
            orderDto.setSetmeal(setmealDao.selectSetmealById(orderDto.getSetmealId()));
            orderDtos.add(orderDto);
        }
        log.info("orders:{}", orders);
        */
        log.info("orders.size():{}", orders.size());
        for (OrderList orderList : orders) {
            log.info("orderList:{}", orderList);
            log.info("orderList:{}", orderList.getName());
            orderList.setSetmealName(setmealDao.findSetmealNameById(orderList.getSetmealId()));
            Report report = reportDao.selectByMemberId(orderList.getMemberId());
            log.info("查询体检报告:{}", report);
            System.out.println(report);
            if (report == null) {
                orderList.setReportStatus("未上传");
            }
            if (report != null) {
                orderList.setId(report.getId());
                orderList.setReportId(report.getId());
                String reportStatus = report.getReportStatus() == 1 ? "已上传" : "已下载";
                orderList.setReportStatus(reportStatus);
            }
        }
        return new PageResult(orderDao.selectTotalByOrderId(queryPageBean.getQueryString()), orders);
    }

    @Override
    public Result saveOrderSettings(OrderList orderList, Integer checkSetmealId) {
        try {
            //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
            String orderDate = DateUtils.parseDate2String(orderList.getOrderDate());
            //预约日期
            OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
            if (orderSetting == null) {
                //指定日期没有进行预约设置，无法完成体检预约
                return Result.error(MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }

            //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
            int number = orderSetting.getNumber();//可预约人数
            int reservations = orderSetting.getReservations();//已预约人数
            if (reservations >= number) {
                //已经约满，无法预约
                return Result.error(MessageConstant.ORDER_FULL);//预约已满
            }
            //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
            String telephone = orderList.getPhoneNumber();//获取用户页面输入的手机号
            Member member = memberDao.findByTelephone(telephone);
            log.info("member:{}", member);
            if (member != null) {
                //判断是否在重复预约
                Integer memberId = member.getId();//会员ID
                /*Date order_Date = DateUtils.parseString2Date(orderDate);*///预约日期
                Order order = new Order(memberId, null, null, null, checkSetmealId);
//                Order order = orderDao.selectOrderByMemberId(memberId);
                //根据会员ID查询出来预约对象
                log.info("根据会员Id查询出来的预约对象:{}", order);
                //根据条件进行查询
                List<Order> list = orderDao.findByCondition(order);
                log.info("查询出来的预约列表:{}", list);
                if (list != null && list.size() > 0) {
                    //说明用户在重复预约，无法完成再次预约
                    return Result.error(MessageConstant.HAS_ORDERED);
                } /*else {
                    //返回提示
                    return Result.error(MessageConstant.MEMBER_REPETITION);
                }*/
            } else {
                //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
                member = new Member();
                member.setFileNumber(orderList.getFileNumber());
                member.setName(orderList.getName());
                member.setPhoneNumber(orderList.getPhoneNumber());
                member.setIdCard(orderList.getIdCard());
                member.setSex(orderList.getSex());
                member.setRegTime(new Date());
                member.setRemark(orderList.getRemark());
                memberDao.insertMember(member);//自动完成会员注册
            }
            //5、预约成功，更新当日的已预约人数,将当前的预约信息进行保存
            Order order = new Order();
            order.setMemberId(member.getId());//设置会员ID
            order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
            order.setOrderType(Order.ORDER_TYPE_EMAIL);//预约类型
            order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
            order.setSetmealId(checkSetmealId);//套餐ID
            orderDao.add(order);//将预约信息保存
            orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
            //设置可预约人数-1
            orderSetting.setNumber(orderSetting.getNumber() - 1);
            orderSettingDao.updateOrderSettingByOrderDate(orderSetting);
            return Result.success(MessageConstant.ORDERSETTING_SUCCESS);//新增成功
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error(MessageConstant.ORDERSETTING_FAIL);//新增失败
        }

    }

    @Override
    public int arrived(Integer id) {
        return orderDao.arrived(id);
    }


}
